package org.apache.jmeter.extractor;

import java.io.Serializable;

import org.apache.jmeter.processor.PostProcessor;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testelement.AbstractScopedTestElement;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterVariables;
import net.minidev.json.JSONArray;
import com.jayway.jsonpath.internal.JsonReader;

public class JSONExtractor extends AbstractScopedTestElement implements PostProcessor, Serializable {
	
	private static final long serialVersionUID = 240L;

	private static final Logger log = LoggingManager.getLoggerForClass();
	
	private static final String REFNAME = "JSONExtractor.refname";
	
	private static final String JSONPATH = "JSONExtractor.JSONPATH";
	
	private static final String DEFAULT = "JSONExtractor.default";

	@Override
	public void process() {
		// TODO Auto-generated method stub
		log.debug("JSONExtractor start to process.");
		JMeterContext context = getThreadContext();
        SampleResult previousResult = context.getPreviousResult();
        
        if (previousResult == null) {
            return;
        }
        
        JMeterVariables vars = context.getVariables();
        String refName = getRefname();
        JsonReader reader = new JsonReader();
        String jsonPath = getJsonpath();
        String defaultS = getDefault();
        
        if (defaultS.length() > 0){
        	vars.put(refName, defaultS);
        }
        Object value = null;
        try{
        	reader.parse(previousResult.getResponseDataAsString());
        	value = reader.read(jsonPath);
        	if (value instanceof JSONArray){
        		log.warn("Result instanceof JSONArray!");
				context.setPreviousResult(previousResult);
        		return;
        	}
        	vars.put(refName, value.toString());  
        	log.debug("put " + refName + " value of " + value.toString());
        }catch(Exception e){
        	log.error("Error Message: " + e.getMessage());
        }
        context.setVariables(vars);
        context.setPreviousResult(previousResult);
        log.debug("JSONExtractor process end.");
	}

	public String getRefname() {
		return getPropertyAsString(REFNAME);
	}

	public void setRefname(String refname) {
		setProperty(REFNAME,refname);
	}

	public String getJsonpath() {
		return getPropertyAsString(JSONPATH);
	}

	public void setJsonpath(String jsonpath) {
		setProperty(JSONPATH,jsonpath);
	}
	
	public String getDefault(){
		return getPropertyAsString(DEFAULT);
	}
	
	public void setDefault(String defaultS){
		setProperty(DEFAULT,defaultS);
	}

}
